#include <stdlib.h>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <stdio.h>

//Screen attributes
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
const int SCREEN_BPP = 32;
int GameState = 0, life=3;

int Xb = 10, Yb = 50;
int dis = 0, dis1=0;
int indice =0;
char dist[30];
Uint8 r,g,b,r1,g1,b1,r2,g2,b2,r3,g3,b3,r4,g4,b4;

int quit = 0;

int X , Y ; 

int bgX = 0, bgY = 0;

int fd;

TTF_Font *textFont;

SDL_Color textColor = {255, 255, 255}, textBgColor = {255, 0, 0};

//The surfaces
SDL_Surface *bird[5];


SDL_Surface *background = NULL;
SDL_Surface *start = NULL;
SDL_Surface *gameOver = NULL;
SDL_Surface *distance = NULL;
SDL_Surface *screen = NULL;
SDL_Surface *bombe =NULL; 

SDL_Surface *bombe1 =NULL;
SDL_Surface *mo =NULL;
SDL_Surface *fish =NULL;
SDL_Surface *fish1= NULL ; 




//The event structure
SDL_Event event;

SDL_Surface *load_image( char* filename )
{
    //The image that's loaded
    SDL_Surface* loadedImage = NULL;

    //Load the image
    loadedImage = IMG_Load( filename );
    loadedImage = IMG_Load( filename );

    //If the image loaded
   
        //If the surface was optimized
        if( loadedImage != NULL )
        {
            //Color key surface
            SDL_SetColorKey( loadedImage, SDL_SRCCOLORKEY, SDL_MapRGB( loadedImage->format, 0, 0xFF, 0xFF ) );
        }
    

    //Return the optimized surface
    return loadedImage;
}

void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
    //Holds offsets
    SDL_Rect offset;

    //Get offsets
    offset.x = x;
    offset.y = y;
    
/*SDL_Event event ;
	    SDL_Init(SDL_INIT_EVERYTHING);
	  ecran= SDL_SetVideoMode(800, 600, 32, SDL_DOUBLEBUF);
          SDL_EnableKeyRepeat(10, 10);
	   i=9; */

    //Blit
    SDL_BlitSurface( source, NULL, destination, &offset );
    
}

int init()
{
    //Initialize all SDL subsystems
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
        return 0;
    }

    //Set up the screen
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //If there was an error in setting up the screen
    if( screen == NULL )
    {
        return 0;
    }

    //Set the window caption
    SDL_WM_SetCaption( "STAGE 3", NULL );

if(TTF_Init() == -1)
    {
        printf("Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError());
        return EXIT_FAILURE;
    }
	textFont = TTF_OpenFont("fonts/african.ttf", 20);
	if(textFont== NULL)
    {
        printf("Erreur loading font ComicPerso.ttf : %s",TTF_GetError());
        exit(-1);
    }

    //If everything initialized fine
    return 1;
}

int load_files()
{

   
    	bird[0] = load_image( "pos1.png" );
	//SDL_SetColorKey(bird[0], SDL_SRCCOLORKEY, SDL_MapRGB(bird[0]->format, 255, 255, 255));
	bird[1] = load_image( "pos2.png" );
	//SDL_SetColorKey(bird[1], SDL_SRCCOLORKEY, SDL_MapRGB(bird[1]->format, 255, 255, 255));
	bird[2] = load_image( "pos3.png" );
	bird[3] = load_image( "pos4.png" );
	bird[4] = load_image( "pos5.png" );
       
       

	//SDL_SetColorKey(bird[2], SDL_SRCCOLORKEY, SDL_MapRGB(bird[2]->format, 255, 255, 255));
  
    	background = load_image( "1.png" );
	start = load_image( "start2.png" );
	gameOver = load_image( "gameOver.png" );
        bombe= load_image( "obstacle3.png" );
        bombe1= load_image("obstacle2.png");
        mo=load_image("mo.png");
        fish=load_image("fish.png");
        fish1=load_image("fish1.png");

        



    //If there was a problem in loading the background
    if( background == NULL )
    {
        return 0;
    }

    return 1;
}

void clean_up()
{ 
    SDL_FreeSurface( start );
    SDL_FreeSurface( bird[0] );
    SDL_FreeSurface( bird[1] );
    SDL_FreeSurface( bird[2] );
    SDL_FreeSurface( bird[3] );
    SDL_FreeSurface( bird[4] );
    
    
    SDL_FreeSurface( background );
    SDL_FreeSurface( gameOver );
    SDL_FreeSurface( distance );
    SDL_FreeSurface( bombe );
    SDL_FreeSurface( bombe1 );
    SDL_FreeSurface( fish1);
    SDL_FreeSurface( mo );
    SDL_FreeSurface(fish);
     SDL_Quit();
}


void getPixelColor(int x, int y, SDL_Surface *map,Uint8 *r,Uint8 *g,Uint8 *b)
{
 
    if(x>0 && y>0 && x<map->w && y<map->h)
    {
        int bpp = map->format->BytesPerPixel;
      
        Uint8 *p = (Uint8 *)map->pixels + y * map->pitch + x * bpp;
        SDL_GetRGB(*(Uint32 *)p,map->format, r, g, b);
 
    }
    else // sinon on renvoie noir, pour éviter de planter dans certains cas
    {
        //r = 255;
        //g = 255;
        //b = 255;
    }
   // printf("r=%u\n",r);
}



int main( int argc, char* args[] )
{
 
    //Initialize
    if( init() == 0 )
    {
        return 1;
    }


    //Load the files
    if( load_files() == 0 )
    {
        return 1;
    }
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    //While the user hasn't quit
    while( quit == 0 )
    {
     SDL_Delay(60);
        //While there's events to handle
        while( SDL_PollEvent( &event ) )
        {
            //If the user has Xed out the window
            if( event.type == SDL_QUIT )
            {
                //Quit the program
		quit = 1;
            }
		 if( event.type == SDL_KEYDOWN )
                {
                    // exit if ESCAPE is pressed
if (event.key.keysym.sym == SDLK_RETURN){
                  if(GameState == 0 || GameState == 2)
			GameState=1;
                   }
                    if (event.key.keysym.sym == SDLK_UP){
if(GameState == 1){
                    Yb-=20;
}
                   }
if (event.key.keysym.sym == SDLK_LEFT){
                    
                   }
if (event.key.keysym.sym == SDLK_RIGHT){
if(GameState == 1){
                        Xb++;


}
if ( Yb <=100)
{ Yb=100;}
                   }

		}
        }

if(GameState == 0){
	apply_surface( 0,0, start, screen );

} else if(GameState == 1){
       
	//Calcul Distance
	dis+=1;
        dis1 = dis/10;

 //Scroll background
        bgX -= 6;
if( bgX <= -background->w )
        {
            //Reset the offset
            bgX = 0;
        }

        //If the background has gone too far
       r= 150;
	g= 150;
	b=150;
getPixelColor(Xb,Yb, screen,&r1,&g1,&b1);
getPixelColor(Xb+bird[indice]->w,Yb, screen,&r2,&g2,&b2);
getPixelColor(Xb+bird[indice]->w,Yb+bird[indice]->h, screen,&r3,&g3,&b3);
getPixelColor(Xb,Yb+bird[indice]->h, screen,&r4,&g4,&b4);
//printf("r1=%d , g1=%d , b1=%d ; r2=%d , g2=%d , b2=%d ; r3=%d , g3=%d , b3=%d ; r4=%d , g4=%d , b4=%d\n",r1,g1, b1,r2,g2, b2,r3,g3, b3,r4,g4, b4);
                                

             if((r1<r && g1<g && b1<b) || (r2<r && g2<g && b2<b) || (r3<r && g3<g && b3<b) || (r4<r && g4<g && b4<b))
                                {
                                Xb =10 ;
				Yb = 150;
				bgX = 0;
                                bgY= 0; 
dis=0; 
dis1=0;
life--;
                                } 



        //Show the background
        apply_surface( bgX, bgY, background, screen );
        apply_surface( bgX + background->w, bgY, background, screen);
        //apply_surface( 300, 300, bombe, screen );
       apply_surface( bgX+150 + bombe1->w, bgY+110, bombe1, screen);
       apply_surface( bgX+150 + bombe1->w, bgY+300, bombe1, screen);
       apply_surface( bgX+300 + bombe->w, bgY+110, bombe, screen);
       apply_surface( bgX+300 + bombe->w, bgY+300, bombe, screen);
       apply_surface( bgX+450 + bombe1->w, bgY+150, bombe1, screen);
       apply_surface( bgX+450 + bombe1->w, bgY+400, bombe1, screen);
       apply_surface( bgX+600 + bombe->w, bgY+110, bombe, screen);
       apply_surface( bgX+600 + bombe->w, bgY+300, bombe, screen);
       apply_surface( bgX+750 + bombe1->w, bgY+150, bombe1, screen);
       apply_surface( bgX+750 + bombe1->w, bgY+400, bombe1, screen);
       apply_surface( bgX+900 + bombe->w, bgY+110, bombe, screen);
       apply_surface( bgX+900 + bombe->w, bgY+400, bombe, screen);
       apply_surface( bgX+1050 + bombe1->w, bgY+150, bombe1, screen);
       apply_surface( bgX+1050 + bombe1->w, bgY+300, bombe1, screen);
       apply_surface( bgX+1200 + bombe->w, bgY+150, bombe, screen);
       apply_surface( bgX+1200 + bombe->w, bgY+300, bombe, screen);
                                 apply_surface( bgX+900 + fish->w, bgY+260, fish, screen);
       apply_surface( bgX+1350 + bombe->w, bgY+110, bombe, screen);
       apply_surface( bgX+1350 + bombe->w, bgY+400, bombe, screen);
                                 apply_surface( bgX+1350 + fish1->w, bgY+260, fish, screen);





        
        //apply_surface( 300,300, bombe, screen );
        
      

	// Show the life's bird
if(life>0)
	apply_surface( SCREEN_WIDTH-10 - bird[0]->w, 20, bird[0], screen );
if(life >1)
apply_surface( SCREEN_WIDTH-20-(bird[0]->w)*2, 20, bird[0], screen );
if(life >2)
apply_surface( SCREEN_WIDTH-30-(bird[0]->w)*3, 20, bird[0], screen );
if(life<=0)
GameState = 2;

        //Show the bird
	
      
        apply_surface( Xb, Yb, bird[indice], screen );
indice= ((indice+1)%5);
Yb+=6;
 


// Show distance
//sprintf(dist, "Distance : %d", dis1);
//distance = TTF_RenderText_Shaded(textFont, dist, textColor, textBgColor);
apply_surface( SCREEN_WIDTH - 170, SCREEN_HEIGHT-20, distance, screen);

	}else if(GameState == 2){
	apply_surface( (SCREEN_WIDTH-100)/2,(SCREEN_HEIGHT-20)/2, gameOver, screen );
	life=3;
}

        //Update the screen
        if( SDL_Flip( screen ) == -1 )
        {
           return 1;
        }

        //Cap the frame rate
      SDL_Delay(50);
    }

    //Clean up
    clean_up();

    return 0;
}
